package com.sinozo.aspectj;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * AOP 统一打印
 *
 * @date 2025/11/1 22:54
 */

@Slf4j
@Aspect
@Component
public class LoggingAspect {

    /**
     * 拦截所有Controller层的public方法
     * @param
     *
     * @date 2025/11/1 22:59
     * @author zhehen.lu
     */
    @Pointcut("execution(public * com.sinozo.controller..*.*(..))")
    public void controllerMethod() {}

    /**
     * 方法调用前打印入参
     * @param joinPoint
     *
     * @date 2025/11/1 22:59
     * @author zhehen.lu
     */
    @Before("controllerMethod()")
    public void logBefore(JoinPoint joinPoint) {
        log.info("请求方法: {}", joinPoint.getSignature().toShortString());
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            log.info("请求参数: {}", arg);
        }
    }

    /**
     * 方法返回后打印出参
     * @param result
     *
     * @date 2025/11/1 22:59
     * @author zhehen.lu
     */
    @AfterReturning(pointcut = "controllerMethod()", returning = "result")
    public void logAfterReturning(Object result) {
        //TODO 结果数据比较大，暂时不打印
        //log.info("返回结果: {}", result);
    }

    /**
     * 异常时打印错误
     * @param e
     *
     * @date 2025/11/1 22:59
     * @author zhehen.lu
     */
    @AfterThrowing(pointcut = "controllerMethod()", throwing = "e")
    public void logAfterThrowing(Throwable e) {
        log.error("方法异常: ", e);
    }
}
